package controller

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
	"uniquen.top/golang-demo/dto"
	"uniquen.top/golang-demo/model"
	"uniquen.top/golang-demo/response"
	"uniquen.top/golang-demo/respository"
	"uniquen.top/golang-demo/validated"
)

type ICategoryController interface {
	RestController
}

type CategoryController struct {
	Repository respository.CategoryRepository
}

func NewCategoryController() ICategoryController {

	repository := respository.NewCategoryRepository()

	repository.DB.AutoMigrate(model.Category{})

	return CategoryController{Repository: repository}
}

func (c CategoryController) Create(ctx *gin.Context) {

	var requestCategory validated.CategoryCreateValidate

	if err := ctx.ShouldBind(&requestCategory); err != nil {
		result, _ := json.Marshal(requestCategory)
		log.Printf("参数错误: %v", string(result))
		response.Fail(ctx, http.StatusUnprocessableEntity, 422, nil, "数据验证错误，分类名称必填")
		return
	}

	if _, err := c.Repository.Create(requestCategory.Name); err != nil {
		response.Fail(ctx, http.StatusInternalServerError, 500, nil, "创建失败")
		return
	}

	response.Success(ctx, nil, "创建成功")
}

func (c CategoryController) Update(ctx *gin.Context) {
	var requestCategory model.Category
	ctx.Bind(&requestCategory)

	if requestCategory.Name == "" {
		response.Fail(ctx, http.StatusUnprocessableEntity, 422, nil, "分类名称必填")
		return
	}
	// 获取path中的参数
	categoryId, _ := strconv.Atoi(ctx.Params.ByName("id"))
	updateCategory, err := c.Repository.Query(categoryId)
	// 如果记录数为0说明搜索结果不存在
	if err != nil {
		response.Fail(ctx, http.StatusBadRequest, 400, nil, "分类不存在")
		return
	}

	category, err := c.Repository.Update(requestCategory.Name, *updateCategory)
	if err != nil {
		response.Fail(ctx, http.StatusInternalServerError, 500, nil, "更新失败")
		return
	}

	response.Success(ctx, gin.H{"category": category}, "更新成功")
}

func (c CategoryController) Show(ctx *gin.Context) {

	categoryId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	if categoryId == 0 {
		response.Fail(ctx, http.StatusUnprocessableEntity, 422, nil, "分类ID必传")
		return
	}
	category, err := c.Repository.Query(categoryId)
	if err != nil {
		//log.Printf("分类不存在: %v", categoryId)
		//response.Fail(ctx, http.StatusBadRequest, 400, nil, "分类不存在")
		panic(err)
		return
	}

	response.Success(ctx, gin.H{"category": dto.ToCategoryDTO(category)}, "查询成功")
}

func (c CategoryController) Delete(ctx *gin.Context) {
	categoryId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	if categoryId == 0 {
		response.Fail(ctx, http.StatusUnprocessableEntity, 422, nil, "分类ID必传")
		return
	}

	if err := c.Repository.Delete(categoryId); err != nil {
		response.Fail(ctx, http.StatusInternalServerError, 500, nil, "删除失败")
		return
	}
	response.Success(ctx, nil, "删除成功")
}
